package com.powernode.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.powernode.reggie.common.CustomException;
import com.powernode.reggie.common.R;
import com.powernode.reggie.dto.DishDto;
import com.powernode.reggie.entity.*;
import com.powernode.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description: 菜品
 * @author: www
 * @time: 2023/3/9 16:24
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //新增需要清理redis方法


        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        //清理redis缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);


        return R.success("新增菜品成功");
    }


    /**
     * 菜品信息分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Dish> pageInfo = new Page<>(page,pageSize);//分页构造器
        Page<DishDto> dishDtoPage = new Page<>();


        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();//条件构造器
        queryWrapper.like(name != null,Dish::getName,name);//过滤条件 name 不为空才加条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);//排序条件

        dishService.page(pageInfo,queryWrapper);//执行分页查询

        //对象拷贝 pageInfo的属性拷贝到dishDtoPage 其中records 属性不拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id

            Category category = categoryService.getById(categoryId);//根据id查分类对象
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息 修改页面回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){//路劲变量注解  R中用DishDto 包括菜品信息和口味信息；
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理所有菜品在redis中的缓存
        Set keys = redisTemplate.keys("dish_*");//查找所有菜品在redis中的key
        redisTemplate.delete(keys);//清理所有菜品的redis缓存

        //只清理更新分类下的redis数据
//        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
//        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }


    /**
     * 根据id删除菜品  可批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){//多个 ID 要使用集合接收时，其前面要加上 @RequestParam 注解。
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }


    /**
     * 启售停售菜品 可批量操作
     * @param status
     * @param ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids){//路径上获得状态

        //停售启售也需要将redis中数据缓存清理掉；删除不用，因为删除需要先停售；
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        //要停售菜品，必须要先停售关联套餐；所以停售需要判断
        if(status == 0){
            //根据菜品id 获取 套餐id
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SetmealDish::getDishId,ids);
            List<SetmealDish> list = setmealDishService.list(queryWrapper);
            Set<Long> setmealIds = new HashSet<>();
            list.forEach(item->{
                Long setmealId = item.getSetmealId();
                setmealIds.add(setmealId);
            });
            if(!setmealIds.isEmpty()){//关联套餐不是空，表示关联了套餐
                LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.in(Setmeal::getId,setmealIds);
                queryWrapper1.eq(Setmeal::getStatus,1);//查询套餐是否在售
                if(setmealService.count(queryWrapper1) > 0){
                    throw new CustomException("停售失败，有关联套餐在售");
                }
            }
        }

        List<Dish> dishes = dishService.listByIds(ids);//根据id查到菜品

        dishes = dishes.stream().map(dish -> {
            dish.setStatus(status);//通过流给菜品状态赋值
            return dish;
        }).collect(Collectors.toList());

        dishService.updateBatchById(dishes);

        return R.success("状态修改成功");
    }

    /**
     * 根据条件查询对应菜品，，categoryId 分类id查对应菜品
     * @param dish
     * @return
     */
   /* @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){//dish 中就有传回的categoryId；通用点

        //构造条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId,dish.getCategoryId());//等值查询
        queryWrapper.eq(Dish::getStatus,1); //指定条件查询状态为1的即在售菜品

        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);//排序条件


        List<Dish> list = dishService.list(queryWrapper);


        return R.success(list);
    }*/

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){//dish 中就有传回的categoryId；通用点

        List<DishDto> dishDtoList = null;

        //先从redis中获取缓存数据  key 根据分类id 和status构造
        String key = "dish_" +dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null){
            //如果存在，就直接返回，无需查询
            return R.success(dishDtoList);
        }

        //构造条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId,dish.getCategoryId());//等值查询
        queryWrapper.eq(Dish::getStatus,1); //指定条件查询状态为1的即在售菜品

        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);//排序条件


        List<Dish> list = dishService.list(queryWrapper);


        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id

            Category category = categoryService.getById(categoryId);//根据id查分类对象
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);//查出菜品的口味

            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());


        //如果不存在，需要查询数据库，将查询结果缓存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);//缓存数据设置60分钟

        return R.success(dishDtoList);
    }

}
